﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Newtonsoft.Json; 

public class UdpLogServer : IDisposable
{
    private readonly UdpClient _udpClient;
    private readonly int _port;
    private bool _isRunning;
    private Thread _receiverThread;

    public event Action<LogEntry> LogReceived;

    public UdpLogServer(int port = 5140)
    {
        _port = port;
        _udpClient = new UdpClient(port);
    }

    public void Start()
    {
        if (_isRunning) return;

        _isRunning = true;
        _receiverThread = new Thread(ReceiveLogs)
        {
            IsBackground = true
        };
        _receiverThread.Start();

        Console.WriteLine($"UDP log server started on port {_port}");
    }

    private void ReceiveLogs()
    {
        IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);

        while (_isRunning)
        {
            try
            {
                byte[] receivedBytes = _udpClient.Receive(ref remoteEndPoint);
                string jsonString = Encoding.UTF8.GetString(receivedBytes);

                var logEntry = JsonConvert.DeserializeObject<LogEntry>(jsonString);
                LogReceived?.Invoke(logEntry);
            }
            catch (SocketException ex) when (ex.SocketErrorCode == SocketError.Interrupted)
            {
                // 正常停止时抛出
                break;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error receiving log: {ex.Message}");
            }
        }
    }

    public void Stop()
    {
        _isRunning = false;
        _udpClient.Close();
        _receiverThread?.Join();
    }

    public void Dispose()
    {
        Stop();
        _udpClient?.Dispose();
    }
}

public class LogEntry
{
    public string Timestamp { get; set; }
    public string Level { get; set; }
    public string Message { get; set; }
    public string Logger { get; set; }
    public string Path { get; set; }
    public int Line { get; set; }

    public override string ToString()
    {
        return $"[{Timestamp}] {Level.ToUpper()} - {Logger}:{Line} - {Message}";
    }
}

// 使用示例
/*class Program
{
    static void Main(string[] args)
    {
       
        using (var logServer = new UdpLogServer(5140))
        {
            logServer.LogReceived += entry =>
            {
                switch (entry.Level.ToUpper())
                {
                    case "ERROR": color = ConsoleColor.Red; break;
                    case "WARNING": color = ConsoleColor.Yellow; break;
                    case "INFO": color = ConsoleColor.Gray; break;
                    case "DEBUG": color = ConsoleColor.Green; break;
                }
            };
            logServer.Start();
        }
        
    }
}*/